package logic

import (
	"context"
	"errors"
	"math/rand"
	"real-free/cache"
	"real-free/pkg"
	"strconv"
	"time"

	"real-free/freerpc/freerpc"
	"real-free/freerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *freerpc.SendSmsRequest) (*freerpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	ints, _ := cache.Rdb.Get(l.ctx, "sendSmsNum"+in.Username).Int()
	if ints > 1 {
		return nil, errors.New("验证码只能发送一次")
	}
	i := rand.Intn(900000) + 100000
	send, err := pkg.Send(in.Username, strconv.Itoa(i))
	if err != nil {
		return nil, err
	}
	if send.Code != 2 {
		return nil, err
	}
	cache.Rdb.Set(l.ctx, "sendSms"+in.Username, i, time.Minute*5)
	result, _ := cache.Rdb.Incr(l.ctx, "sendSmsNum"+in.Username).Result()
	if result == 1 {
		cache.Rdb.Expire(l.ctx, "sendSmsNum"+in.Username, time.Minute*1)
	}

	return &freerpc.SendSmsResponse{}, nil
}
